const express = require('express');
const uuid = require('node-uuid');
const { Message,MessageList } = require('../utils/message');
const costModel = require('../models/cost');

const router = express.Router();

router.post('/',(req,res,next)=>{
  const {name,price,number,cost,costDate,purpose} = req.body;
  const id = uuid.v1();
  const costs = new costModel({id,name,price,number,cost,costDate,purpose});
  costs.save().then(data=>{
    if(data){
      res.json(Message(200,'添加成功！'));
    }
  });
});

router.delete('/',(req,res,next)=>{
  const {id}=req.query;
  if(id){
    costModel.deleteOne({id}).then(data=>{
      if(data.deletedCount!==0){
        res.json(Message(200,'删除成功！'))
      }else{
        res.json(Message(400,'删除失败'))
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'))
  }
})

router.put('/',(req,res,next)=>{
  const {id}=req.query;
  const {name,price,number,cost,costDate,purpose}=req.body;
  if(id){
    costModel.updateOne({id},{name,price,number,cost,costDate,purpose}).then(data=>{
      if(data.acknowledged&&data.modifiedCount!==0){
        res.json(Message(200,'修改成功！'));
      }else{
        res.json(Message(400,'修改失败！'));
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'));
  }
})

router.get('/',(req,res,next)=>{
  const {id,page,pageSize}=req.query;
  const queryObj={};
  if(id) {
    queryObj.id=id
    costModel.findOne({id}).then(data=>{
      if(data){
        res.json(Message(200,'',data))
      }else{
        res.json(Message(400,'未查找到相关数据！'));
      }
    })
    return
  };
  if(page&&pageSize){
    costModel.find(queryObj).count((err,count)=>{
      costModel.find(queryObj)
        .limit(pageSize)
        .skip((page-1)*pageSize)
        .then(data=>{
          res.json(MessageList(200,'',data,page,pageSize,count));
        })
    })
  }
})

router.get('/echartsData',(req,res,next)=>{
  const {time}=req.query;
  const st=new Date(time.toString());
  let str=st.getFullYear()+'-'+(st.getMonth()+2);
  const et=new Date(str);
  const queryObj={};
  queryObj.$and=[{costDate: {'$gte': st}},{costDate: {'$lt': et}}]
  const arr=[];
  // for(let i=0;i<12;i++){
  //   arr[i]=0;
  // }
  costModel.find(queryObj).count((err,count)=>{
    costModel.find(queryObj).then(data=>{
      let chartsData=[]
      data.forEach((item,index)=>{
        const obj={}
        obj.name=item.purpose
        obj.value=item.cost
        chartsData.push(obj)
      })
      chartsData=compare(chartsData,'name','value')
      res.json(MessageList(200,'',chartsData,0,0,0))
    })
  })
  function compare(arr,judgeKey,mergeKey){
    let result=[];
    arr.forEach(item=>{
        let index=-1;
        result.forEach((m,n)=>{
            if(m[judgeKey]==item[judgeKey]){
                index=n;
            }
        });
        if(index!=-1){
            result[index][mergeKey]+=item[mergeKey];
        }else{
            result.push(item);
        }
    });
    return result;
  }
})

module.exports = router